#!/usr/bin/python
# coding=utf-8
"""
Control the various servers used when testing
"""
__revision__ = "$Id: control.py 46 2007-03-12 09:42:24Z jens.persson $"

import sqlobject


def setup_database():
    """
    Find the database that is used
    """
    from turbogears import database
    cfg = open(join(dirname(__file__), "../dev.cfg")).read()
    line = [l for l in cfg.splitlines() if l.startswith('sqlobject.dburi')][-1]
    dburl = line.split("=", 1)[1].strip("\"'")
    database.set_db_uri(dburl)

def empty_database():
    """
    Clean out the database, using the SQLobjects direct
    """
    import worde.model
    module = worde.model
    names = worde.model.__dict__
    classes = [names[c] for c in names
               if isinstance(names[c], type)
                  and issubclass(names[c], sqlobject.SQLObject)
                  and names[c].__module__ == module.__name__]
    for c in classes:
        try:
            c.dropTable()
        except:
            pass
        c.createTable()

import os
from os.path import dirname, join, normpath, split

class Service(object):
    """
    A service wrapper. Given a command, it can start and stop it
    """
    def __init__(self, filename, args = []):
        """
        set up the class

        file should be a runable command
        """
        self._pid = None
        self._path, self._command = split(filename)
        self._path = normpath(join(dirname(__file__), self._path))
        self._args = args


    def start(self):
        """
        Start the service

        changes the working directory to the one containing the program
        """
        if not self._pid:
            cwd = os.getcwd()
            os.chdir(self._path)
            self._pid = os.spawnv(os.P_NOWAIT, join(".", self._command), self._args)
            os.chdir(cwd)

    def stop(self):
        """
        Stop the service
        """
        os.kill(self._pid, 15)
        self._pid = None

selenium = Service("../external/selenium/server/start")
worde = Service("../start-worde.py", ["testing.cfg"])